package com.lnlyj.imagtext;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * wanglei 2020-02-22 11:31
 */
public class HtmlUtils {

    private static final String TAG = "HtmlUtils";

    public static List<ImageBean> filterImages(String compatText) {
        List<ImageBean> list = new ArrayList<>();
        if (!TextUtils.isEmpty(compatText) && compatText.contains("<img")) {
            //get img src
            Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");//<img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
            Matcher m = p.matcher(compatText);

            while (m.find()) {

                String searchAttr = "src";
                String regForTagAttr = searchAttr + "\\s*=\\s*[\"|']([\\s\\S]*)[\"|']";//"=[\"|']([^[\"|']]+)[\"|']";
                Pattern patternForAttr = Pattern.compile(regForTagAttr);
                Matcher matcherForAttr = patternForAttr.matcher(m.group());
                if (matcherForAttr.find()) {
                    ImageBean bean = new ImageBean();
                    bean.setSrc(m.group());
                    bean.setPath(matcherForAttr.group(1));
                    bean.setStart(m.start());
                    bean.setEnd(m.end());
                    list.add(bean);
                }
            }

        }
        return list;
    }
}
